import time

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

# 实例化Options来创建启动参数对象
options = webdriver.ChromeOptions()
# 启动无痕模式运行
options.add_argument('--incognito')
# 设置窗口最大化运行
options.add_argument('--start-maximized')
# 取消Chrome正受到自动测试软件的控制的提示
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option("excludeSwitches", ['enable-automation'])
# 启动浏览器
driver = webdriver.Chrome(options=options)
# 设置隐式等待
driver.implicitly_wait(3)
# 防止被反爬
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
    Object.defineProperty(navigator, 'webdriver', {
      get: () => false
    })
  """
})

# 访问百度首页
driver.get('https://www.baidu.com/')
time.sleep(3)

# 定位右上角的设置按钮
settings = driver.find_element(By.CSS_SELECTOR, 'div#u1 > span')
# 借助鼠标行为链实现鼠标悬停操作
ActionChains(driver).move_to_element(settings).perform()
# 点击搜索设置
driver.find_element(By.CSS_SELECTOR, 'a.setpref').click()
time.sleep(3)
# 点击保存设置
driver.find_element(By.LINK_TEXT, '保存设置').click()
time.sleep(3)
# 打印弹框信息
print(driver.switch_to.alert.text)
# 接受弹框
driver.switch_to.alert.accept()
time.sleep(3)

# 退出浏览器
driver.quit()
